<template>
  <view class="page">
    <!-- 车辆展示 -->
    <view class="hero">
      <image class="hero-img" :src="pic" mode="widthFix" />
      <text class="hero-cap">{{name}}</text>
    </view>

    <!-- 计费规则 -->
    <view class="section">
      <view class="sec-title">计费规则</view>
      <view class="rules-wrap">
        <view class="rule-item">
          <text class="rule-label">起步价</text>
          <text class="rule-value">{{ qibujia }}元</text>
        </view>
        <view class="rule-item">
          <text class="rule-label">时长费</text>
          <text class="rule-value">{{scf}}</text>
        </view>
        <view class="rule-item">
          <text class="rule-label">押金</text>
          <text class="rule-value">{{ yajin}}元</text>
        </view>
      </view>
      <view class="note">说明：骑行服务费是在已开始服务时刻所对应的计费规则为准</view>
    </view>

    <!-- 底部大按钮 -->
    <view class="cta-wrap" v-if="pay_yajin == 1">
      <button class="cta" @tap="jiesuo" v-if="status == 0">解锁用车</button>
	  <button class="cta" v-else>使用中</button>
    </view>
	<!-- 底部大按钮 -->
	<view class="cta-wrap" v-else>
	  <button class="cta" @tap="param_to_url('recharge_yajin?type=2&rowid='+rowid+'&money='+yajin)">前往支付押金</button>
	</view>
  </view>
</template>

<script>
import common_config from '../../static/js/common.js';
var config = common_config.config;
var that;	
var userInfo;
export default {
  data() {
    return {
	  name:'',
	  pic:'',
	  yajin:'',
	  rowid:'',
	  orderrowid:'',
	  scf:'',
	  qibujia:'',
	  open_row_id:'',
	  status:0,
      fee: {
        base: 0,          // 起步价（元）
        unit: 0,          // 单位时长价格（元）
        unitMinutes: 0,   // 单位分钟
        deposit: 0        // 押金（元）
		
      },
	  act:'',
	  pay_yajin:0
    };
  },
  onLoad(query) {
	that = this;
	if(query.rowid){
		that.rowid = query.rowid;
	}
	if(query.q){
		var params = that.getQueryParams(decodeURIComponent(query.q || ""));
		that.act = params.act;
		if(params.act == 'unlock' || params.act == 'lock'){
			that.rowid = params.rowid;
		}
	}
    // 你可以从路由参数或接口带入真实费率；这里做示例默认值
    this.fee = {
      base: Number(query.base || 0),
      unit: Number(query.unit || 0),
      unitMinutes: Number(query.unitMinutes || 0),
      deposit: Number(query.deposit || 0)
    };
	that.plusReady();
  },
  methods: {
	  getQueryParams(url) {
	    let query = url.split("?")[1];
	    let params = {};
	    query.split("&").forEach(part => {
	      let [key, value] = part.split("=");
	      params[key] = value;
	    });
	    return params;
	  },
	  param_to_url(url){
		  uni.navigateTo({
		  	url:url
		  })
	  },
	  //初始化
	  plusReady(){
	  	userInfo = uni.getStorageSync('userInfo');
	  	if(userInfo){
	  		userInfo = JSON.parse(userInfo);
	  		that.if_login = true;
	  		that.member_profile = userInfo;
			if(that.act == 'lock'){
				that.get_orders();
				return false;
			}
			that.load_datas();
			that.load_row_id();
			
	  	}else{
	  		that.if_login = false;
			uni.redirectTo({
				url:'/pages/index/login'
			});
			return false;
	  	}
	  	
	  },
	scan_back(order_rowid){
	  uni.request({
	    url: config.request_url+'/v2/open/worksheet/editRow',
	    method: 'POST',
	    header: { 'Content-Type': 'application/json' },
	    data: {
	      "appKey": config.appKey,
	      "sign": config.sign,
	      "worksheetId": "ddgl",
	      "triggerWorkflow": true,
		  "rowId":order_rowid,
		  "controls": [
		      {
		        "controlId": "ddzt",
		        "value": "还车中"
		      },
		      {
		        "controlId": "ghddpad",
		        "value": that.rowid // 归还地点Pad的rowid (扫归还二维码获取的)
		      }
		    ]
	    },
	    success: (res) => {
	      res = res.data;
	      if(res.success){
	        var datas = res.data;
			uni.showToast({
				title:'车辆归还中，请稍后'
			});
			setTimeout(function(){
				uni.switchTab({
					url:'/pages/index/me'
				});
			},1000);
	      }else{
	        uni.showToast({ title: res.data?.msg || '数据获取失败', icon: 'none' });
	      }
	    },
	    fail: (err) => {
	      console.error('请求失败:', err);
	      uni.showToast({ title: '网络错误', icon: 'none' });
	    }
	  })  
	},
	//获取当前用户订单状态
	get_orders(){
	  uni.request({
	    url: config.request_url+'/v2/open/worksheet/getFilterRows',
	    method: 'POST',
	    header: { 'Content-Type': 'application/json' },
	    data: {
	      "appKey": config.appKey,
	      "sign": config.sign,
	      "worksheetId": "ddgl",
	      "pageSize":50,
	      "pageIndex":1,
		  "filters": [
			  {
				  "controlId": "yonghu",
				  "dataType": 29,
				  "spliceType": 1,
				  "filterType": 24,
				  "value": userInfo.rowid//用户记录的rowid
			  },
			  {
				  "controlId": "ddzt",
				  "dataType": 11,
				  "spliceType": 1,
				  "filterType": 1,
				  "value": '使用中'
			  }
		  ]
	    },
	    success: (res) => {
	      res = res.data;
	      if(res.success){
	        var datas = res.data;
			if(datas.rows.length < 1){
				uni.showModal({
					title:'您当前没有待还车订单',
					showCancel:false,
					success() {
						uni.switchTab({
							url:'/pages/index/index'
						});
					}
				})
				return false;
			}
			that.scan_back(datas.rows[0].rowid);
	      }else{
	        uni.showToast({ title: res.data?.msg || '数据获取失败', icon: 'none' });
	      }
	    },
	    fail: (err) => {
	      console.error('请求失败:', err);
	      uni.showToast({ title: '网络错误', icon: 'none' });
	    }
	  })  
	},
    goBack() {
      if (getCurrentPages().length > 1) {
        uni.navigateBack();
      } else {
        uni.switchTab({ url: '/pages/home/home' });
      }
    },
    onMenu() {
      uni.showActionSheet({
        itemList: ['费用说明', '联系客服'],
        success: (res) => {
          if (res.tapIndex === 0) uni.showModal({ title: '费用说明', content: '以下单时展示为准。' });
          if (res.tapIndex === 1) uni.makePhoneCall({ phoneNumber: '400-000-0000' });
        }
      });
    },
	load_row_id(){
		uni.request({
		  url: config.request_url+'/v2/open/worksheet/getFilterRows',
		  method: 'POST',
		  header: {
			'Content-Type': 'application/json'
		  },
		  data: {
			"appKey": config.appKey,
			"sign": config.sign,
			"worksheetId": "yhgl",
			"pageSize": 50,
			"pageIndex": 1,
			"filters": [
				{
					"controlId": "openid",
					"dataType": 2,
					"spliceType": 1,
					"filterType": 2,
					"value": userInfo.openid //传openid
				}
			]
		  },
		  success: (res) => {
			console.log('返回结果:', res.data);
			res = res.data;
			console.log(res);
			if(res.success){
				var datas = res.data.rows;
				for(var i = 0;i < datas.length;i++){
					if(datas[i].openid == userInfo.openid){
						that.open_row_id = datas[i].rowid;
						if(datas[i].yajin > 0){
							that.pay_yajin = 1;
						}
						break;
					}
				}
			}else{
				 uni.showToast({ title: res.data.msg || '数据获取失败', icon: 'none' });
			}
		  },
		  fail: (err) => {
			console.error('请求失败:', err);
			uni.showToast({ title: '网络错误', icon: 'none' });
		  }
		})  
	},
	load_datas(n){
		uni.request({
		  url: config.request_url+'/v2/open/worksheet/getRowByIdPost',
		  method: 'POST',
		  header: {
			'Content-Type': 'application/json'
		  },
		  data: {
			"appKey": config.appKey,
			"sign": config.sign,
			"worksheetId": n == 'jiesuo'? 'ddgl':'zdgl',
			"rowId":n == 'jiesuo' ? that.orderrowid:that.rowid
		  },
		  success: (res) => {
			console.log('返回结果:', res.data);
			res = res.data;
			console.log(res);
			if(res.success){
				if(n == 'jiesuo'){
					if(res.data.jszt == '解锁成功'){
						uni.hideLoading();
						uni.showToast({
							title:'解锁成功'
						});
						that.status = 1;
					}else if(res.data.jszt == '解锁失败'){
						uni.hideLoading();
						uni.showToast({
							title:'解锁失败，请联系客服人员'
						});
					}else{
						setTimeout(function(){
							that.load_datas(n);
						},1000);
					}
					return false;
				}
				that.name = res.data.sbflmc;
				var r = JSON.parse(res.data.tupian);
				console.log(r);
				that.pic = r[0].original_file_full_path;
				//that.fee.base = res.data.qibujia;
				that.scf = res.data.scjf;
				that.yajin = res.data.yajin;
				that.qibujia = res.data.qibujia;
			}else{
				 uni.showToast({ title: res.data.msg || '数据获取失败', icon: 'none' });
			}
		  },
		  fail: (err) => {
			console.error('请求失败:', err);
			uni.showToast({ title: '网络错误', icon: 'none' });
		  }
		})  
	},
	jiesuo(){
		uni.showLoading({
			title:'解锁中'
		});
		uni.request({
		  url: config.request_url+'/v2/open/worksheet/addRow',
		  method: 'POST',
		  header: {
			'Content-Type': 'application/json'
		  },
		  data: {
			"appKey": config.appKey,
			"sign": config.sign,
			"worksheetId": "ddgl",
			"controls": [
				{
					"controlId": "ddzt",
					"value": "使用中"
				},
				{
					"controlId":"jszt",
					"value":"未解锁"
				},
				{
					"controlId": "yonghu",
					"value":that.open_row_id//用户记录rowid
				},
				{
					"controlId": "shebei",
					"value":that.rowid //设备记录rowid
				},
				{
					"controlId": "jine",
					"value":"0"
				}
			]
		  },
		  success: (res) => {
			console.log('返回结果:', res.data);
			res = res.data;
			console.log(res);
			that.orderrowid = res.data;
			that.load_datas('jiesuo');
		  },
		  fail: (err) => {
			console.error('请求失败:', err);
			uni.showToast({ title: '网络错误', icon: 'none' });
		  }
		})  
	},
	//轮询订单
	change_order(){
		uni.request({
		  url: config.request_url+'/v2/open/worksheet/addRow',
		  method: 'POST',
		  header: {
			'Content-Type': 'application/json'
		  },
		  data: {
			"appKey": config.appKey,
			"sign": config.sign,
			"worksheetId": "ddgl",
			"controls": [
				{
					"controlId":"ddkssj",
					"value":"2025-9-9 23:40:00" //订单开始时间  String（2018-8-8 12:00:00）
				},
				{
					"controlId": "ddzt",
					"value": "使用中"
				},
				{
					"controlId":"jszt",
					"value":"未解锁"
				},
				{
					"controlId": "yonghu",
					"value":userInfo.openid //用户记录rowid
				},
				{
					"controlId": "shebei",
					"value":that.rowid //设备记录rowid
				},
				{
					"controlId": "jine",
					"value":"0"
				}
			]
		  },
		  success: (res) => {
			console.log('返回结果:', res.data);
			res = res.data;
			console.log(res);
			
		  },
		  fail: (err) => {
			console.error('请求失败:', err);
			uni.showToast({ title: '网络错误', icon: 'none' });
		  }
		})  
	},
    scan() {
      // 微信端扫码示例
      // #ifdef MP-WEIXIN
      wx.scanCode({
        success: (ret) => {
          uni.showToast({ title: '扫码成功', icon: 'success' });
          // 解析二维码后可自动带入车辆编号等
        },
        fail: () => uni.showToast({ title: '取消扫码', icon: 'none' })
      });
      // #endif
    },
    unlock() {
      // TODO: 调用你的后端接口进行解锁操作
      uni.showLoading({ title: '正在解锁' });
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({ title: '解锁成功', icon: 'success' });
        // 解锁后跳转到骑行进行中页面
        // uni.redirectTo({ url:'/pages/ride/ongoing?orderId=xxx' })
      }, 800);
    }
  }
};
</script>

<style lang="scss" scoped>
$bg:#f6f6f6;$blue:#0075B8;
.page{background:$bg;min-height:100vh;padding-bottom:calc(env(safe-area-inset-bottom) + 120rpx);}
.nav{position:sticky;top:0;z-index:10;background:#fff;padding:calc(var(--status-bar-height,0px)) 24rpx 16rpx;display:grid;grid-template-columns:1fr auto 1fr;align-items:center;border-bottom:1rpx solid rgba(0,0,0,0.04);}
.nav-left{justify-self:start;padding:10rpx;}
.nav-right{justify-self:end;display:flex;gap:20rpx;}
.nav-btn{padding:10rpx;}
.nav-ico{width:36rpx;}
.nav-title{justify-self:center;font-size:36rpx;font-weight:700;color:#222;}
/* 替换原来的 .hero 行 */
.hero{background:#e8e8e8;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:140rpx 24rpx;}

.hero-img{width:560rpx;}
.hero-cap{margin-top:16rpx;color:#8a8f98;font-size:26rpx;}
.section{padding:24rpx;}
.sec-title{font-size:32rpx;font-weight:700;color:#333;margin:12rpx 0 16rpx;}
.rules-wrap{background:#dedede;border-radius:24rpx;padding:18rpx;}
.rule-item{background:#fff;border-radius:16rpx;height:96rpx;display:flex;align-items:center;justify-content:space-between;padding:0 24rpx;margin:12rpx 0;}
.rule-label{font-size:28rpx;color:#333;}
.rule-value{font-size:28rpx;color:#111;}
.note{margin-top:10rpx;color:#9aa0a6;font-size:22rpx;}
.cta-wrap{position:fixed;left:0;right:0;bottom:env(safe-area-inset-bottom);padding:24rpx 32rpx 32rpx;background:transparent;}
.cta{width:100%;height:100rpx;line-height:100rpx;text-align:center;border-radius:999rpx;background:$blue;color:#fff;font-size:34rpx;font-weight:700;}
.cta::after{border:none;}
</style>
